<?php
namespace Todo\Model\Rate;

use Todo\Model\BaseModel;

class ScoreModel extends BaseModel
{
    protected $order = 'id DESC';

    public $tableName = 'rate_score';

    public $_validate = array(
        array('record_id', 'require', '请选择项目'),
        array('norm_id', 'require', '必须选择指标'),
        array('score', 'require', '分数不能为空')
    );
    
    protected $_auto = array(
        array('tnt_id', 'auto_tnt', self::MODEL_INSERT, 'function')
    );

    public function saveScore($norm, $record, $val=false){
        if($val == false) $val = I('post.norm_'. $norm['id']);
        $val = floatval($val);
        if( $val > $norm['score'] || ($norm['min'] && $val < $norm['min']) || ($norm['max'] && $val > $norm['max'])) {
            $this->error = '存在无效的分数!';
            return false;
        }
        $data = array(
            'record_id' => $record['id'],
            'norm_id' => $norm['id']
        );
        $old =  $this->where($data)->find();
        if($old){
            $ret = $this->where(array('id'=>$old['id']))->save(array('score'=>$val));
        }else{
            $data['score'] = $val;
            $data['tnt_id'] = auto_tnt();
            $ret = $this->add($data);
        }

        return $ret !== false;
    }
}